#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
class WorklogsAreLinkedToAssignments < ActiveRecord::Migration
  def self.up
    add_column "worklogs", "assignment_id", :integer

    Worklog.reset_column_information
    Worklog.find(:all).each do |w|
      w.assignment_id = Assignment.find_by_user_id_and_project_id(w.worker_id, w.project_id).id
      w.update
    end

    remove_index "worklogs", :name => "fk_worklog_project"
    remove_index "worklogs", :name => "fk_worklog_worker"

    remove_column "worklogs", "project_id"
    remove_column "worklogs", "worker_id"

    add_index "worklogs", ["assignment_id"], :name => "fk_worklog_assignment"
  end

  def self.down
    add_column "worklogs", "worker_id", :integer
    add_column "worklogs", "project_id", :integer

    Worklog.reset_column_information
    Worklog.find(:all).each { |w|
      a = Assignment.find(w.assignment_id) 
      w.project_id = a.project_id
      w.worker_id = a.user_id
      w.update
    }

    remove_index "worklogs", :name => "fk_worklog_assignment"
    remove_column "worklogs", "assignment_id"

    add_index "worklogs", ["project_id"], :name => "fk_worklog_project"
    add_index "worklogs", ["worker_id"], :name => "fk_worklog_worker"
  end
end
